I'm confused with the "this"keyword in JS. I understand that rabbit's prototype is animal and the "this" keyword in rabbit.isSleeping should refer to rabbit but I thought the animal.isSleeping should refer to animal I don't understand why it's undefined? Could someone explain?
let animal = {
walk() {
if (!this.isSleeping) {
alert(`I walk`);
}
},
sleep() {
this.isSleeping = true;
}
};
let rabbit = {
name: "White Rabbit",
__proto__: animal
};
rabbit.sleep();
alert(rabbit.isSleeping); // true
alert(animal.isSleeping)
When a property is assigned to an object - here, when you do
this.isSleeping = true;
The engine will first examine the instance, then its internal prototype, and so on up to the beginning of the prototype chain - to identify the first such object that has an isSleeping property. If an object is found, and it's a setter, the setter is invoked. Otherwise, no matter where the property is found, the instance is assigned the property (as a data property, of course).
When you do
rabbit.sleep();
the instance is rabbit - that's the this inside the method. And there are no isSleeping setters, so
sleep() {
this.isSleeping = true;
}
results in the instance - the rabbit object - receiving the property. So the animal object remains unchanged.
Unless there are getters/setters involved somewhere, doing
someObj.someProp = someVal
will always and only ever result in someObj being mutated, while keeping its internal prototype(s) unchanged.